<?php
/**
 * M1跟单移交列表
 */

namespace app\admin\model;
use think\Db;

class Recovery extends Common
{
    protected $name = 'apply';



    /**
     *回收列表
     * @param $keywords
     * @param int $page
     * @param int $limit
     * @param $valuedate
     * @param string $os
     * @param string $status
     * @return mixed
     * @AUTHER 范俊成
     * @Email gakiismywife1@163.com
     * @DATE 2018/5/23
     */
    public function getDataList($keywords, $page=1, $limit=15, $valuedate, $os = '',$status = "")
    {
        $offset = $page==1?0:($page-1)*$limit;

        $sql = "select a.id,c.create_time,a.order_number,a.name,a.phone,a.huishou_claim_date,a.money,a.appoint_time,a.mobile_type,a.huishou_claim_date,a.uid,a.fk_time from qh_apply a INNER JOIN qh_consignment c on c.apply_id=a.order_number where a.huishou_status=1 AND (a.huishou_aid is null or a.huishou_aid = '')";
        $sql_count = "select count(*) from qh_apply a INNER JOIN qh_consignment c on c.apply_id=a.order_number where a.huishou_status=1 AND (a.huishou_aid is null or a.huishou_aid = '')";
        if($os){
            $sql .= ' and os ='.$os;
            $sql_count .= ' and os ='.$os;
        }
        if($valuedate){
            $start = date('Y-m-d H:i:s',strtotime($valuedate));
            $end = date('Y-m-d H:i:s',strtotime("$valuedate +1day"));

            $sql .= " and c.create_time between '$start' and '$end'  ";
            $sql_count .= " and c.create_time between '$start' and '$end'  ";
        }
        if ($keywords){
            $sql .= " and (phone = '$keywords' or name = '$keywords' or order_number = '$keywords' )";
            $sql_count .= " and (phone = '$keywords' or name = '$keywords' or order_number = '$keywords')";
        }
        $sql .= ' order by    c.create_time  desc limit '.$limit.' offset '.$offset;
        $list = $this->query($sql);
        $dataCount = $this->query($sql_count);
        foreach ($list as $k=>$v){
            $list[$k]['huishou_way'] = '邮寄';
            $list[$k]['last_huishouyuan'] = $this->alias('a')
                ->join('admin_user u','a.huishou_aid = u.id')
                ->where(array('a.uid'=>$v['uid']))
                ->where('a.status','=',5)
                ->field('u.realname')
                ->order('a.time desc')
                ->find()['realname'];
        }

        //去除重复的邮寄 只留最新的一笔邮寄订单
        $room = array();
        foreach ($list as $key => $value){
            if(!isset($room[$value['order_number']])){
                $room[$value['order_number']] = $key;
            }elseif (isset($room[$value['order_number']]) && strtotime($value['create_time'])>strtotime($list[$room[$value['order_number']]]['create_time'])){

                unset($list[$room[$value['order_number']]]);
                $room[$value['order_number']] = $key;
            }else{
                unset($list[$key]);
            }
        }


        $data['list'] = $list;
        $data['dataCount'] = $dataCount[0]['count(*)'];
        return $data;
    }

    /**
     *回收列表
     * @param $keywords
     * @param int $page
     * @param int $limit
     * @param $valuedate
     * @param string $os
     * @param string $status
     * @return mixed
     * @AUTHER 范俊成
     * @Email gakiismywife1@163.com
     * @DATE 2018/5/23
     */
    public function getDataList_bak($keywords, $page=1, $limit=15, $valuedate, $os = '',$status = "")
    {

        if($keywords){
          $map['a.name|a.phone|a.order_number'] = $keywords;
        }
        $list = $this->alias('a')
              ->join('consignment c','a.order_number = c.apply_id')
              ->where('a.huishou_status',1)
              ->whereNull('a.huishou_aid')
              ->where('c.status','<>','3')
              ->where($map)
              ->where('a.order_number not in (select apply_id from qh_consignment where status =3)')
              ->field('a.time,a.name,a.phone,a.fk_time,a.appoint_time,a.money,c.create_time,a.mobile_type,a.uid')
              ->page($page,$limit)
              // ->fetchSql(true)
              ->select();

        $dataCount = $this->alias('a')
              ->join('consignment c','a.order_number = c.apply_id')
              ->where('a.huishou_status',1)
              ->whereNull('a.huishou_aid')
              ->where('c.status','<>','3')
              ->where($map)
              ->where('a.order_number not in (select apply_id from qh_consignment where status =3)')
              ->field('count(*)')
              // ->fetchSql(true)
              ->find();
        foreach ($list as $key => $value) {
          // code...
            $user = $this->alias('a')
                    ->join('admin_user u','a.huishou_aid = u.id')
                    ->where('a.time','<',$value['time'])
                    ->where('uid',$value['uid'])
                    ->order('time desc')
                    ->field('u.realname')
                    ->find();
                    // echo $this->getLastSql();exit;
            $list[$key]['last_huishouyuan'] = $user['realname'];
            $list[$key]['huishou_way'] = '邮寄';
        }

        $data['list '] = $list;
        $data['dataCount'] = $dataCount['count(*)'];
        return $data;
    }
    /**
     * [getDataById 根据主键获取详情]
     * @zhanhuiping
     * @DateTime  2017-02-10T21:16:34+0800
     * @param     string                   $id [主键]
     * @return    [array]
     */
    public function getDataById($id = '')
    {

        $data=$this->alias('a')
            ->join('qh_user_info b','a.uid = b.uid')
            ->field('overdue_money,huishou_visit,a.contract_number,a.is_report,a.delay_rate,a.credit_rate,a.period,a.credit_rate*a.period*a.money as rental,a.mobile_type,b.wechat_id,b.city,b.payday,a.bank_card_number,a.name,a.phone,b.age,b.sex,b.qq,b.zhima,b.province,b.id_card_img1,
                    b.id_card_img2,b.id_card_img3,b.tb_address,b.wx_wallet,b.alipay_bill,
                    b.wyjt_img,b.wyjt_hk_img,b.open_gid,b.id_card,b.mon_income,b.company,
                    b.company_ads,a.uid,a.money,a.time,a.check_aid,a.check_time,a.check2_aid,
                    a.check2_time,a.merchandiser,a.treasurer,a.fk_time,a.hk_time,a.period,
                    a.appoint_time,a.order_number,a.contract_number,a.rate,a.overdue_rate,a.service_rate,
                    a.procedure_rate,a.credit_rate,a.review,a.remark,b.operator_outUniqueId,a.meets,b.uid,a.upload_img,a.status,b.address,a.return_visit,b.negative_img,b.wechat_img,a.id,a.hang,a.descnote,b.zmf,is_loaning,b.job,b.directories')
            ->where('a.id',$id)
            ->find();
//        echo $this->getLastSql();exit;
        if($data){
            $data=$data->toArray();
        }

        $data['overdue_day'] = $this->getOverdueDay($data); //逾期天数

        //物流信息
        $map['apply_id'] = $data['order_number'];
        $express = Db::name('consignment')->where($map)->order('create_time desc')->find();
        $express['express_num'] = $express['logistics_no'];
        $express['express_name'] = $express['logistics_company'];
        $data += $express;
        $uid = $this->field('uid')->where('id',$id)->find()->toArray();

		$map['uid'] = $uid['uid'];

        unset($map['apply_id']);

        //历史借款记录
        $historyrecord = $this->where($map)
            ->with(['predelay'])
            ->field('uid,id,fourth_claim_date,third_claim_date,time,remark,review,time,phone,status,order_number,check_aid,check_time,check2_aid
          ,check2_time,merchandiser,merchandiser2,treasurer,fk_time,hk_time,money,appoint_time,name,phone,return_visit,refuse_to_lend_money')->select();
        $historyrecord = modelo2array($historyrecord);
        foreach($historyrecord as $key=>$value) {
            $map1['id'] = $value['check_aid'];
            $map2['id'] = $value['check2_aid'];
            $map3['id'] = $value['merchandiser'];
            $map4['id'] = $value['treasurer'];
            $map5['id'] = $value['merchandiser2'];//催收员

            $check_aiddata = Db('admin_user')->field('username')->where($map1)->find();
            $check2_aiddata = Db('admin_user')->field('username')->where($map2)->find();
            $merchandiserdata = Db('admin_user')->field('username')->where($map3)->find();
            $treasurerdata = Db('admin_user')->field('username')->where($map4)->find();
            $merchandiser2 = Db('admin_user')->field('username')->where($map5)->find();


            $historyrecord[$key]['check_aid'] = $check_aiddata['username'];
            $historyrecord[$key]['check2_aid'] = $check2_aiddata['username'];
            $historyrecord[$key]['merchandiser'] = $merchandiserdata['username'];
            $historyrecord[$key]['treasurer'] = $treasurerdata['username'];
            $historyrecord[$key]['merchandiser2'] = $merchandiser2['username'];

            #延期+还款
            if ($historyrecord[$key]['predelay']) {
                foreach ($historyrecord[$key]['predelay'] as $k => $v) {
                    if (strpos($v['no_order'], 'XQ') === false) {
                        $historyrecord[$key]['predelay'][$k]['ishk'] = 1;

                        if ($historyrecord[$key]['fourth_claim_date'] < $historyrecord[$key]['predelay'][$k]['pay_time']
                            && !is_null($historyrecord[$key]['fourth_claim_date'])
                        ) {
                            $historyrecord[$key]['predelay'][$k]['role'] = 'M1';//角色
                            $historyrecord[$key]['predelay'][$k]['roleName'] = $merchandiser2['username'];//角色姓名
                        } else {
                            $historyrecord[$key]['predelay'][$k]['role'] = 'M0';//角色
                            $historyrecord[$key]['predelay'][$k]['roleName'] = $merchandiserdata['username'];//角色姓名
                        }

                        //催收备注表
                        $whereRN['apply_id'] = $value['id'];
                        $whereRN['admin_uid'] = $GLOBALS['userInfo']['id'];
                        $whereRN['uid'] = $value['uid'];
                        $reminder = Db::name('reminder_note')->where($whereRN)->order('id desc')->find();
                        $historyrecord[$key]['predelay'][$k]['contact'] = $reminder['contact_type'];//联系方式
                        $historyrecord[$key]['predelay'][$k]['remark'] = $reminder['reminder_status'];//备注
                        $historyrecord[$key]['predelay'][$k]['contact_name'] = $reminder['contact_name'];//联系姓名方式
                    }
                }
            }

        }
        $data['history'] = $historyrecord;

        $result = getExpressInfo($express['logistics_no']);
        if($express['return_no']){
            $return = getExpressInfo($express['return_no']);
            $data['return_info'] = $return;
        }else{
            $data['return_info'] = array('code'=>400,'data'=>'没有退货物流');
        }
        $data['logistics_info'] = $result;

        return $data;
    }

    /**
     * 回收认领
     * @param array $param
     * @return bool
     */
    public function claim($id,$uid,$admin_uid)
    {
         $map['id'] = $id;
         $info = $this->field('huishou_aid')->where($map)->find();
         if($info['huishou_aid'])
         {
           return $data = ['code'=>'error','message'=>'已经被认领'];
         }

        $data = array();
        $data['huishou_claim_date'] = date('Y-m-d H:i:s',time());
        $data['huishou_aid'] = $admin_uid;
        $res = $this->where($map)->update($data);
        if(!$res){
            $this->error = '领取失败';
            return false;
        }
        return $data = ['code'=>'success','message'=>'领取成功'];
    }



    /**
     * 历史延期
     * @author cxr <1481746137@qq.com>
     * @return $this
     */
    public function predelay(){
//        $where_yanqi['qh_user_order.no_order'] = ['like', '%XQ%']; // 总
        $where_yanqi['result_pay'] = ['eq', 'SUCCESS'];
        return $this->hasMany('UserOrder','apply_id','order_number')->where($where_yanqi);
    }




}
